<%--
  Created by IntelliJ IDEA.
  User: kaigejava
  Date: 2019/12/8
  Time: 10:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<jsp:include page="/commons/taglib.jsp"/>
<html>
<head>
    <title>聊天室</title>
    <script  src="../../js/jquery-1.12.3.min.js"></script>
</head>
<body>
<div>
    <h1>欢迎 ${userName},登陆聊天系统.<div id="users"></div>
    <input type="hidden" id = "userName"/></h1>
</div>

<div>
    <input id="text" type="text"/>
    <button onclick="sendMsg()">给系统发送消息</button>
    <br>
    <button onclick="closeSocket()">关闭连接</button>
</div>

<!-- 消息展示区-->
<div id="message">

</div>

</body>


<script>
    $(document).ready(function() {
        $.post("onlineusers",function(data){
            for(var i=0;i<data.length;i++)
                $("#users").append('<a href="#" onclick="talk(this)" class="list-group-item">'+data[i]+'</a>');
        });
    });
        // 指定websocket路径
        var websocket;
        var userName = '${userName}';
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://localhost:8082/tomcatWebSocket/"+userName);
        } else if ('MozWebSocket' in window) {
            websocket = new MozWebSocket("ws://localhost:8082/tomcatWebSocket/"+userName);
        } else {
            websocket = new SockJS("http://localhost:8082/tomcatWebSocket/"+userName);
        }

        //当发生错误的时候提示
        websocket.onerror=function(){
            setMessageInnerHTML("连接发生了错误");
        }

        //连接成功提示
        websocket.onopen=function() {
            setMessageInnerHTML("欢迎连接到websocket服务器");
        }

        //收到消息
        websocket.onmessage=function(ev){
            var top="系统消息：";
            setMessageInnerHTML(top+ev.data);

        }
        //连接关闭的回调方法
        websocket.onclose = function () {
            setMessageInnerHTML("WebSocket连接关闭");
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            closeWebSocket();
        }

        //将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            document.getElementById('message').innerHTML += innerHTML + '<br/>';
        }
        //关闭WebSocket连接
        function closeSocket() {
            websocket.close();
        }

        //发送消息
        function sendMsg() {
            var message = $("#userName").val()+$("#text").val();
            websocket.send(message);
        }
</script>
</html>
